﻿<%@ WebHandler Language="C#" Class="ChangeLogHandler" %>

using System;
using System.Web;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using Chenxin.Lib.Utility;

public class ChangeLogHandler : AjaxHandlerBase
{
    public ChangeLogHandler()
    {
    }

    override public void RequestProcess(HttpContext context)
    {
        string strOp = context.Request["op"];
        string strResponse = "";
        switch (strOp.ToLower())
        {
            case "getlist":
                strResponse = getChangeLogList(context);
                break;
            default:
                break;
        }
        context.Response.Write(strResponse);
    }

 

    private string getChangeLogList(HttpContext context)
    {
        try
        {
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
            string fieldlist = "HB_OprPerson,HB_OprDepart,HB_OprPersonId,HB_OprDepartId,HB_CompanyId,HB_CityId,RecordId,HouseId,HouseCode,HouseAddress,ChangTime,Operater,OperaterCode,OperaterId,OprDepartId,OprDepart,OprCompanyId,OprCompany,OprCityId,OprCity,SourceState,TargetState,OprType";
            string fieldtablelist = "H.OprPerson as HB_OprPerson,H.OprDepart as HB_OprDepart, H.OprPersonId as HB_OprPersonId,H.OprDepartId as HB_OprDepartId, H.CompanyId as HB_CompanyId,H.CityId as HB_CityId,C.RecordId,C.HouseId,C.HouseCode,C.HouseAddress,C.ChangTime,C.Operater,C.OperaterCode,C.OperaterId,C.OprDepartId,C.OprDepart,C.OprCompanyId,C.OprCompany,C.OprCityId,C.OprCity,Case C.SourceState when '10' then '有效' when '-1' then '无效' when '20' then '暂缓' when '30' then '封盘' when '-10' then  '已删除' end as SourceState,case C.TargetState  when '10' then '有效' when '-1' then '无效' when '20' then '暂缓' when '30' then '封盘' when '-10' then  '已删除' end as TargetState,C.OprType";
            string orderfield = (string.IsNullOrEmpty(context.Request["sort"])) ? "C.ChangTime desc" : context.Request["sort"];

            Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
            Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid employee = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);

            string stime = context.Request["stime"];
            string etime = context.Request["etime"];
            string strquery = context.Request["strquery"];
            string personCode = context.Request["personCode"];
            string state = context.Request["state"];
            string housepersonCode = context.Request["housepersonCode"];
            string targetState = context.Request["targetState"];
            
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            //修改
            if (string.IsNullOrEmpty(state) || "10".Equals(state))
            {
                sb.Append("(1=1)");
                if (employee != Guid.Empty)
                    sb.AppendFormat(" AND (C.OperaterId = '{0}') ", employee);
                else if (departs != Guid.Empty)
                    sb.AppendFormat(" AND (C.OprDepartId = '{0}')", departs);
                else if (businessdistrict != Guid.Empty)
                {
                    Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                    string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
                    Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                    item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                    if (!cs.Hit)
                    {
                        item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                        if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                    }

                    if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失");

                    sb.Append(" AND (EXISTS(");
                    sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
                    sb.AppendFormat("WHERE (C.OprDepartId = M.Departid AND M.DepartSrc like '{0}%'))) ", item.DepartSrc);
                }
                else if (company != Guid.Empty)
                    sb.AppendFormat(" AND (C.OprCompanyId ='{0}')", company);
                else if (city != Guid.Empty)
                {
                    sb.Append(" AND (EXISTS(");
                    sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
                    sb.AppendFormat("WHERE (C.OprDepartId = M.Departid AND M.CityId = '{0}%'))) ", city);
                }
                else
                {
                    sb.AppendFormat(" AND (C.OprCompanyId ='{0}')", CurrentUserInfo.CompanyId);
                }

                //************逻辑范围***********************************/
                if (CurrentUserInfo.ContainsPermit(Constants.Permit_HouseChange_ViewAll))
                {
                }
                else if (CurrentUserInfo.ContainsPermit(Constants.Permit_HouseChange_ViewCity))
                {
                    sb.Append(" AND (EXISTS(");
                    sb.Append("Select 1 from v_Hr_DepartmentInfo N ");
                    sb.AppendFormat("WHERE (C.OprDepartId = N.Departid AND  N.CityId= '{0}'))) ", CurrentUserInfo.CityId);
                }
                else if (CurrentUserInfo.ContainsPermit(Constants.Permit_HouseChange_ViewCompany))
                {
                    sb.AppendFormat(" AND (C.OprCompanyId ='{0}')", CurrentUserInfo.CompanyId);
                }
                else
                {
                    sb.Append(" AND (1 <> 1) ");
                }

            } else{
                sb.Append("(1=1)");

                if (employee != Guid.Empty)
                    sb.AppendFormat(" AND (H.OprPersonId = '{0}') ", employee);
                else if (departs != Guid.Empty)
                    sb.AppendFormat(" AND (H.OprDepartId = '{0}')", departs);
                else if (businessdistrict != Guid.Empty)
                {
                    Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                    string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
                    Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                    item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                    if (!cs.Hit)
                    {
                        item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                        if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                    }

                    if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失");

                    sb.Append(" AND (EXISTS(");
                    sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
                    sb.AppendFormat("WHERE (H.OprDepartId = M.Departid AND M.DepartSrc like '{0}%'))) ", item.DepartSrc);
                }
                else if (company != Guid.Empty)
                    sb.AppendFormat(" AND (H.CompanyId ='{0}')", company);
                else if (city != Guid.Empty)
                {
                    sb.Append(" AND (EXISTS(");
                    sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
                    sb.AppendFormat("WHERE (H.OprDepartId = M.Departid AND M.CityId = '{0}%'))) ", city);
                }
                else
                {
                    sb.AppendFormat(" AND (H.CompanyId ='{0}')", CurrentUserInfo.CompanyId);
                }

                //************逻辑范围***********************************/
                if (CurrentUserInfo.ContainsPermit(Constants.Permit_HouseChange_ViewAll))
                {
                }
                else if (CurrentUserInfo.ContainsPermit(Constants.Permit_HouseChange_ViewCity))
                {
                    sb.Append(" AND (EXISTS(");
                    sb.Append("Select 1 from v_Hr_DepartmentInfo N ");
                    sb.AppendFormat("WHERE (H.OprDepartId = N.Departid AND  N.CityId= '{0}'))) ", CurrentUserInfo.CityId);
                }
                else if (CurrentUserInfo.ContainsPermit(Constants.Permit_HouseChange_ViewCompany))
                {
                    sb.AppendFormat(" AND (H.CompanyId ='{0}')", CurrentUserInfo.CompanyId);
                }
                else
                {
                    sb.Append(" AND (1 <> 1) ");
                }
            }
        
            if (!String.IsNullOrEmpty(stime))
            {
                sb.Append(string.Format(" AND convert(varchar(10),(convert(datetime,C.ChangTime,120)),120)  >= '{0}'", (stime)));
            }
            if (!String.IsNullOrEmpty(etime))
            {
                sb.Append(string.Format(" AND convert(varchar(10),(convert(datetime,C.ChangTime,120)),120)  <= '{0}'", (etime)));
            }
            if (!String.IsNullOrEmpty(strquery))
            {
                sb.AppendFormat(" AND (C.HouseAddress LIKE '%{0}%' OR C.HouseCode LIKE '%{0}%')", strquery);
            }
            if (!String.IsNullOrEmpty(personCode))
            {
                sb.Append(string.Format(" AND (C.OperaterCode ='{0}')", personCode));
            }
            if (!String.IsNullOrEmpty(housepersonCode))
            {
                Chenxin.Lib.Passport.Entity.Hr_UserInfo hr = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityByCode(housepersonCode);
                if (hr == null)
                {
                    sb.Append(" AND (1 <> 1)");
                }
                else
                {
                    sb.AppendFormat(" AND (H.OprPersonId = '{0}')", hr.UserId);
                }
            }
            if (!String.IsNullOrEmpty(targetState))
            {
                sb.Append(string.Format(" and C.TargetState ='{0}'", targetState));
            }
            //判断权限范围结束////////////////////////////////////////////


            System.Data.DataSet list = null;
            list = Chenxin.Lib.House.DAL.ChangeLog.GetList(iPageIndex, iPageSize, orderfield, "ChangeLog C left join House_BaseInfo H on C.HouseId = H.HouseId", sb.ToString(), fieldlist, fieldtablelist, true);
            int count = (int)list.Tables[1].Rows[0][0];
            string strHtml = "";
            if (!GetKeyListHtml(list, out strHtml))
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误:" + strHtml);
            }
            list.Dispose();
            list = null;
            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',html:'{2}'}}}}", "成功", count, strHtml);
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
        }
    }

  
    /// <summary>
    /// 返回列表；
    /// 根据查询参数生成查询条件1,根据权限设定生成查询条件2；
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private bool GetKeyListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        try
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
            {
                sb.AppendFormat("<dl id=\"{0}\">", row["RecordId"].ToString());
               // sb.AppendFormat("<dd>{0}</dd>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseCode", ""));
                sb.AppendFormat("<dd><a href=\"ShowDetailInfo.aspx?houseid={1}\" target=\"blank\">{0}</a></dd>",
                  Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseAddress", ""),
                  Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseId", Guid.Empty));
                sb.AppendFormat("<dd>{0:yyyy-MM-dd HH:mm}</dd>", Convert.ToDateTime(Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ChangTime", "")));
                sb.AppendFormat("<dd>{0}</dd>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Operater", ""));
                sb.AppendFormat("<dd>{0}</dd>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "SourceState", ""));
                sb.AppendFormat("<dd>{0}</dd>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TargetState", ""));
                sb.AppendFormat("<dd>{0}</dd>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OprType", ""));
                sb.AppendFormat("<dd>{0}</dd>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HB_OprPerson", ""));
                sb.AppendFormat("<dd>{0}</dd>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HB_OprDepart", ""));
                sb.Append("</dl>");
            }

            strHtml = sb.ToString();
            return true;
        }
        catch (Exception ex)
        {
            strHtml = ex.Message;
            return false;
        }
    }
}